from config.config import config
import os
import pymysql
from pymysql.err import IntegrityError
import requests


def setup_logging():
    import sys
    """
    配置日志记录并设置控制台输出编码为 UTF-8
    确保日志输出的中文不会出现乱码问题。
    """
    # 设置控制台输出编码为 UTF-8
    sys.stdout.reconfigure(encoding='utf-8')


setup_logging()

# 可以在这里使用 config 字典中的配置信息，例如打印数据库主机地址
print(f"{config}")

conn = pymysql.connect(
    host=config["host"],
    port=config["port"],
    user=config["user"],
    password=config['password'],
    database=config['database'],
    charset="utf8mb4"
)


def sql(sql):
    conn = pymysql.connect(
        host=config["host"],
        port=config["port"],
        user=config["user"],
        password=config['password'],
        database=config['database'],
        charset="utf8mb4",
        utocommit=True,  # 自动提交事务
        connect_timeout=1000  # 连接超时时间（秒）
    )

    cursor = conn.cursor()
    cursor.execute(sql)
    print(cursor.fetchall())
    conn.close()


def insert_data(table_name, data_list):
    """
    批量插入数据到指定表
    :param table_name: 表名
    :param data_list: 要插入的数据列表，每个元素是一个字典，键为列名，值为列值
    """
    if not data_list:
        return
    # 每次调用时创建新的数据库连接
    conn = pymysql.connect(
        host=config["host"],
        port=config["port"],
        user=config["user"],
        password=config['password'],
        database=config['database'],
        charset="utf8mb4",
        # 修正拼写错误
        autocommit=True,  # 自动提交事务
        connect_timeout=10  # 连接超时时间（秒）
    )
    # 找出所有字典共有的键
    common_keys = set(data_list[0].keys())
    for data in data_list[1:]:
        common_keys = common_keys.intersection(data.keys())
    columns = ', '.join(common_keys)
    values_placeholders = ', '.join(['%s'] * len(common_keys))
    insert_query = f"INSERT INTO {table_name} ({columns}) VALUES ({values_placeholders})"
    cursor = conn.cursor()
    successful_inserts = 0
    for data in data_list:
        try:
            # 确保 data 字典的键顺序和 columns 里的列名顺序一致
            data_tuple = tuple(data[col] for col in common_keys)
            cursor.execute(insert_query, data_tuple)
            successful_inserts += 1
        except IntegrityError:
            print(f"数据 {data.get('id')} 已存在，跳过该条数据。")
            conn.rollback()
    # 关闭游标
    cursor.close()
    # 关闭数据库连接
    conn.close()
    print(f"成功插入 {successful_inserts} 条数据到 {table_name} 表")


def read_high_risk_works(dir_path, file_name):
    """
    读取指定路径下的高危作品.txt文件内容，并将每一行数据作为数组元素返回。
    :param dir_path: 高危作品.txt文件所在的目录的绝对路径
    :param file_name: 高危作品.txt文件名
    :return: 包含文件每一行内容的列表
    """
    file_path = os.path.join(dir_path, file_name)
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            lines = file.readlines()
            # 去除每行末尾的换行符
            return [line.strip() for line in lines]
    except FileNotFoundError:
        print(f"未找到文件: {file_path}")
        return []
    except Exception as e:
        print(f"读取文件时发生错误: {e}")
        return []


def save_zip_files(data_list, page):
    """
    遍历传入的数据列表，若子项中包含 pdfStorePath，
    则将对应的 zip 文件保存到以子项 name 属性命名的文件夹中，该文件夹位于 'down' 文件夹下。

    :param data_list: 包含数据项的列表，每个数据项是一个字典
    :param page: 用于发起请求的 DrissionPage 库的 page 对象
    """
    # 创建 'down' 文件夹
    down_folder = os.path.join(os.getcwd(), 'down')
    try:
        if not os.path.exists(down_folder):
            os.makedirs(down_folder)
    except OSError as e:
        print(f"创建 'down' 文件夹时出错: {e}")
        return

    for data in data_list:
        pdf_file_url = data.get('pdfStorePath')
        if pdf_file_url:
            folder_name = data.get('name')
            if folder_name:
                # 在 'down' 文件夹下创建以 name 属性命名的文件夹
                folder_path = os.path.join(down_folder, folder_name)
                try:
                    if not os.path.exists(folder_path):
                        os.makedirs(folder_path)
                except OSError as e:
                    print(f"创建 {folder_name} 文件夹时出错: {e}")
                    continue

                # 处理 pdfStorePath
                if pdf_file_url.endswith('.zip'):
                    try:
                        # 使用 DrissionPage 的 page 对象发起 GET 请求
                        response = page.get(pdf_file_url)
                        # 检查 response 是否为有效的响应对象
                        if hasattr(response, 'status_code'):
                            # 检查响应状态码
                            if response.status_code == 200:
                                file_name = os.path.basename(pdf_file_url)
                                file_path = os.path.join(folder_path, file_name)
                                with open(file_path, 'wb') as f:
                                    f.write(response.content)
                                print(f"成功保存 {file_name} 到 {folder_path}")
                            else:
                                print(f"下载 {pdf_file_url} 失败，状态码: {response.status_code}")
                        else:
                            print(f"请求 {pdf_file_url} 未返回有效的响应对象: {response}")
                    except Exception as e:
                        print(f"下载 {pdf_file_url} 时发生错误: {e}")


if __name__ == "__main__":
    # 示例数据
    data_to_process = [
        {
            "id": 22193515,
            "oid": "CEE1F91982F14CF8BEB44843C342C9C6",
            "userId": 320439464,
            "parentId": 320439464,
            "applicant": "格力律师团队格力律师团队格力律师团队格力律师团队",
            "name": "33",
            "serialNo": "TSA-05-20250404490671443",
            "applyFileStorePath": "https://tsa-sign-pdf.oss-cn-beijing.aliyuncs.com/recorder/320439464/22193515/TSA-05-20250404490671443.zip?Expires=1743888135&OSSAccessKeyId=LTAI4G6VxxDngRZCTfkKX4nP&Signature=ojt0O3mbpVsQZZyj3aoqrbESLQ8%3D&response-content-disposition=attachment%3Bfilename%2A%3Dutf-8%27%2733.zip&response-content-type=application%2Foctet-stream",
            "pdfStorePath": "https://tsa-sign-pdf.oss-cn-beijing.aliyuncs.com/sign/4/320439464/20250404490671443/TSA-05-20250404490671443.zip?Expires=1743888135&OSSAccessKeyId=LTAI4G6VxxDngRZCTfkKX4nP&Signature=wK6P81Yn6nuJJJBSDkfciVLAg2I%3D&response-content-disposition=attachment%3Bfilename%2A%3Dutf-8%27%2733_%25E5%258F%25AF%25E4%25BF%25A1%25E6%2597%25B6%25E9%2597%25B4%25E6%2588%25B3%25E8%25AF%2581%25E4%25B9%25A6.zip&response-content-type=application%2Foctet-stream",
            "videoStorePath": "https://tsa-evidence-pro.oss-cn-beijing.aliyuncs.com/recorder/320439464/22193515/%E6%97%B6%E9%97%B4%E6%88%B3%E5%8F%96%E8%AF%81%E8%A7%86%E9%A2%91_20250404194801.mp4?Expires=1743888135&OSSAccessKeyId=LTAI4G6VxxDngRZCTfkKX4nP&Signature=%2FgO13qtgkaxZX9N%2FkfzmHSKwNCQ%3D",
            "vncEndpoint": "http://47.95.36.75:8080?token=21036f5da1994af78897b4bd70117117",
            "consumeNumberTotal": 5,
            "oweTsCount": 0,
            "startAt": 1743767279000,
            "endAt": 1743767888000,
            "sharingStatus": 0,
            "status": 5,
            "signedCount": 0,
            "returnStatus": 0,
            "createdBy": "320439464",
            "createdAt": 1743767279000,
            "updatedBy": "320439464",
            "updatedAt": 1743767279000,
            "delFlag": 0,
            "remark": "",
            "applicantAccount": "15510016669",
            "evidenceTabStatus": 4,
            "evidenceTabStatusName": "已完成",
            "shareFileType": "VIDEO_ZIP",
            "tsaAt": 1743767903000,
            "oldRecorder": 0,
            "tsaStorePathUrl": "https://tsa-sign-pdf.oss-cn-beijing.aliyuncs.com/sign/4/320439464/20250404490671443/TSA-05-20250404490671443.tsa?Expires=1743888135&OSSAccessKeyId=LTAI4G6VxxDngRZCTfkKX4nP&Signature=VGxIYwREk%2BiOr%2BdfRXRpzMQLjp0%3D&response-content-disposition=attachment%3Bfilename%2A%3Dutf-8%27%2733.tsa&response-content-type=application%2Foctet-stream",
            "channel": 0,
            "pdfWriteRemark": 0,
            "pdfWriteName": 1,
            "releaseStatus": 0,
            "operate": 1,
            "sampleStatus": 0,
            "overseas": 0,
            "approveStatus": 0
        }
    ]
    # 这里需要传入一个 DrissionPage 的 page 对象，示例中无法提供真实对象，仅作示意
    # 实际使用时需要替换为真实的 DrissionPage 的 page 对象
    # 这里假设 page 是一个 DrissionPage 的 page 对象
    # page = ChromiumPage()
    # save_zip_files(data_to_process, page)
